<template>
  <div>
    <!-- 面包屑 -->
    <heima-crumbs secondTitle="权限管理" ThirdTitle="角色列表"></heima-crumbs>
    <!-- 内容主体区 -->
    <el-card>
      <el-row>
        <!-- 添加按钮 -->
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolelist">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染外层结构 -->
            <!-- 循环的时候，是循环 el-row -->
            <el-row
              class="vcenter"
              :class="{ buttom: true, top: index1 === 0 }"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              closable
              @close="removeRightById(scope.row, item3.id)"
            >
              <!-- 一级权限 -->
              <!-- 注意 el-col 中的 span 一般设置成 24 块-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  class="vcenter"
                  :class="{ top: index2 !== 0 }"
                  v-for="(item2, index2) in item1.children"
                  :key="index2.id"
                >
                  <el-col :span="7">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="17">
                    <!-- 渲染三级权限 -->
                    <el-tag
                      type="warning"
                      :class="{ top: index3 !== 0 }"
                      v-for="(item3, index3) in item2.children"
                      :key="index3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetDialogVisible"
      width="30%"
      @close="onSetRightDailogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SetRightDailogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 导入接口模块
import {
  getRolesList,
  deleteRightsById,
  getRightList,
  SetRightDailogList
} from '@/api/roles'
export default {
  name: 'Roles',
  data() {
    return {
      //     所有角色列表数据
      rolelist: [],
      showSetDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: [],
      // 添加权限时当前的 id 值
      roleId: []
    }
  },
  methods: {
    async loadRolesList() {
      try {
        const res = await getRolesList()
        if (res.meta.status === 200) {
          this.rolelist = res.data
        } else {
          this.$message.success(res.meta.msg)
        }
      } catch (error) {
        this.$message.eror(error.msg)
      }
    },
    async removeRightById(role, rightId) {
      try {
        await this.$confirm('您确认删除该权限吗？')
        console.log('您已删除该权限！')
        // 删除指定角色下的权限
        const res = await deleteRightsById(role.id, rightId)
        if (res.meta.status === 200) {
          this.$message.success('删除成功！')
          role.children = res.data
        } else {
          this.$message.error('删除失败！')
        }
      } catch (error) {
        this.$message.info('您取消了操作！')
      }
    },

    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const res = await getRightList()
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限出错！')
      }
      // 所有权限
      this.rightsList = res.data
      this.getLeafKeys(role, this.defkeys)
      this.showSetDialogVisible = true
    },
    // 分配权限确认按钮
    async SetRightDailogConfirm() {
      try {
        // 定义一个数组，接受树形控件的参数
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        // 因为接口的要求是 以 ，形式分割的字符串，所以需要进行二次拼接
        const key = keys.join(',')

        // 将两个参数传给 对应的接口
        const res = await SetRightDailogList(this.roleId, key)

        console.log(this.roleId)
        console.log(res)
      } catch (error) {
        console.log('res')
      }
      this.showSetDialogVisible = false
    },
    // 自己定义的一个递归函数
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含
      // children属性，则是三级节点

      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    onSetRightDailogClosed() {
      this.defkeys = []
    }
  },

  mounted() {
    // 钩子函数 调用 上面方法中定义的 获取数据方法
    this.loadRolesList()
  }
}
</script>
<style lang="less" scope>
.el-tag {
  margin: 8px;
}
.buttom {
  border-bottom: 1px solid #eee;
}
.top {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
